package com.zsh.web;

import com.zsh.pojo.Cart;
import com.zsh.pojo.Order;
import com.zsh.pojo.OrderItem;
import com.zsh.pojo.User;
import com.zsh.service.OrderService;
import com.zsh.service.impl.OrderServiceImpl;
import com.zsh.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class OrderServlet extends BaseServlet {

        private OrderService orderService = new OrderServiceImpl();
        /**
         * 生成订单
         * @param request
         * @param response
         * @throws ServletException
         * @throws IOException
         */
        protected void createOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Cart cart = (Cart) request.getSession().getAttribute("cart");

            User loginUser = (User) request.getSession().getAttribute("user");


            if (loginUser ==null){
                response.sendRedirect(request.getContextPath()+"/pages/user/login.jsp");
                return;
            }

            Integer userId = loginUser.getId();
//            System.out.println(request.getSession());

            String orderId = orderService.createOrder(cart, userId);

            request.getSession().setAttribute("orderId",orderId);

            response.sendRedirect(request.getContextPath()+"/pages/cart/checkout.jsp");
        }

        protected void showMyOrders(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            User loginUser = (User) request.getSession().getAttribute("user");
            if (loginUser ==null){
                response.sendRedirect(request.getContextPath()+"/pages/user/login.jsp");
                return;
            }
            Integer userId = loginUser.getId();
            List<Order> orders = orderService.showMyOrders(userId);

            request.getSession().setAttribute("orders",orders);

            response.sendRedirect(request.getContextPath()+"/pages/order/order.jsp");

        }

        protected void showOrderDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String orderId = request.getParameter("orderId");

            List<OrderItem> orderItems = orderService.showOrderDetail(orderId);
            request.getSession().setAttribute("orderItems",orderItems);

            response.sendRedirect(request.getContextPath()+"/pages/order/orderDetail.jsp");
            //request.getRequestDispatcher(request.getContextPath()+"/pages/order/orderDetail.jsp").forward(request,response);


        }
}
